#include <iostream>
#include <fstream>
#include <sstream>

int main() {
    std::ifstream tcpFile("/proc/net/tcp");
    std::string line;

    // 跳过文件头部分
    std::getline(tcpFile, line);

    // 逐行读取并解析TCP连接信息
    while (std::getline(tcpFile, line)) {
        std::istringstream iss(line);
        std::string localAddress, remoteAddress, state;

        // 忽略不需要的字段
        for (int i = 0; i < 7; i++) {
            iss >> std::ws;
            if (i == 1) {
                iss >> localAddress;
            } else if (i == 2) {
                iss >> remoteAddress;
            } else if (i == 3) {
                iss >> state;
            } else {
                std::string discard;
                iss >> discard;
            }
        }

        // 解析本地地址和端口
        std::istringstream localIss(localAddress);
        std::string localIP, localPort;
        std::getline(localIss, localIP, ':');
        std::getline(localIss, localPort, ':');

        // 解析远程地址和端口
        std::istringstream remoteIss(remoteAddress);
        std::string remoteIP, remotePort;
        std::getline(remoteIss, remoteIP, ':');
        std::getline(remoteIss, remotePort, ':');

        std::cout << "LocalAddr: " << localIP
                  << ", LocalPort: " << std::stoi(localPort, nullptr, 16)
                  << ", RemoteAddr: " << remoteIP
                  << ", RemotePort: " << std::stoi(remotePort, nullptr, 16)
                  << ", State: " << state
                  << std::endl;
    }

    tcpFile.close();
    return 0;
}